package com.cqie.hospitalescort.config.provider;

import com.cqie.hospitalescort.DTO.AuthUser;
import com.cqie.hospitalescort.service.login.UserDetailService.WxUserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class WeChatAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private WxUserDetailServiceImpl userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String openid = authentication.getName();
        AuthUser user = userDetailsService.loadUserByUsername(openid);

        if (user == null) {
            throw new UsernameNotFoundException("用户未找到: " + openid);
        }

        //对于微信登录，忽略密码验证
        return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
